'use strict';

const Controller = require('egg').Controller;
const httpx = require('httpx');
const uuid = require('node-uuid');
const { appid, secret, grant_type, code2session } = require('../constants/wechat');
const WXBizDataCrypt = require('../constants/WXBizDataCrypt');

class WechatController extends Controller {
  /**
   * 获取openid 和 session_key
   **/
  async getSessionKey() {
    const { ctx, ctx: { service } } = this;
    const { code: js_code } = ctx.request.body;

    if (!js_code) {
      return ctx.fail('code is required.');
    }

    ctx.logger.info('**********根据code获取openid和session_key**********');

    try {
      let data;
      const url = ctx.helper.urlParams(code2session, {
        appid,
        secret,
        js_code,
        grant_type,
      });

      const response = await httpx.request(url);
      const text = await httpx.read(response, 'utf8');
      data = JSON.parse(text);

      // data = {
      //   "errMessage": null,
      //   "errCode": null,
      //   "data": {
      //     "session_key": "JLqb0h7GJ+wrZPmO8pOHnQ==",
      //     "openid": "ocs6k5MlJwpstZv_vUdK8NqMXEks"
      //   }
      // }

      if (data.errcode) {
        const err = new Error(data.errmsg);
        err.name = 'WeChatAPIError';
        err.code = data.errcode;
        return ctx.error(err);
      }

      const openid = await service.sessionKey.find({ openid: data.openid });
      const thirdSession = uuid.v1().replace(/-/g, '');

      if (openid.length === 1) {
        // 已有该用户，修改thirdSession
        await service.sessionKey.update({ openid: data.openid }, {
          session_key: data.session_key,
          thirdSession,
        });
      } else {
        // 未有该用户，增加
        await service.sessionKey.create({ ...data, thirdSession, });
      }

      ctx.success({
        thirdSession,
      });

    } catch (err) {
      ctx.error(err);
    }
  }

  /**
   * 解码encryptedData获取用户敏感数据
   **/
  async decode() {
    const { ctx, ctx: { service } } = this;
    const { thirdSession, encryptedData, iv } = ctx.request.body;

    if (!thirdSession) {
      return ctx.fail('thirdSession is required.');
    }
    if (!encryptedData) {
      return ctx.fail('encryptedData is required.');
    }
    if (!iv) {
      return ctx.fail('iv is required.');
    }

    ctx.logger.info('**********解密encryptedData获取用户数据**********');
    try {
      const session = await service.sessionKey.find({ thirdSession });

      const pc = new WXBizDataCrypt(appid, session[0].session_key);
      const data = pc.decryptData(encryptedData, iv);

      ctx.success(data);
    } catch (err) {
      ctx.error(err);
    }
  }
}

module.exports = WechatController;
